<template>
<div class="padding_15">
  <div class="app-page bg-white">
    <!-- 页面内容 -->
    <div class="page-body bg-white">
      <div class="flex space-between align-center">
        <div class="full-width">
         
               <!-- 页面头部 -->
            <div class="page-header flex align-center space-between" style="display:flex;padding: 22px 20px 22px 0px;">
              <div>
                <el-button @click="backMarket">返回分销市场</el-button>
                <el-button @click="addgoods">添加商品</el-button>
              </div>
              <div class="buttonDel">
                <el-button type="info" @click="VolumeSet">批量设置</el-button>
                <el-button type="danger" @click="BatchDelel">批量删除</el-button>
            </div>
            </div>
          
          <el-form :inline="true" ref="form" :model="form" size="small" style="display: inline-block!important;vertical-align: bottom;">
            <el-form-item label="商品名称：">
              <el-input size="small" placeholder="请输入商品名称" v-model="form.goodsName"></el-input>
            </el-form-item>
            <el-form-item label="商品分类：">
              <el-cascader :options="options" placeholder="请选择商品分类" :show-all-levels="false" v-model="categoryId"
                          :props="{ value: 'id',label:'title',children:'goodsCategoryModelList' }"></el-cascader>
            </el-form-item>
            <el-form-item label="售价：">
              <el-col :span="11">
                <el-input style="width: 100%;" v-model="form.minPrice" placeholder="0"></el-input>
              </el-col>
              <el-col class="line" :span="2">—</el-col>
              <el-col :span="11">
                <el-input style="width: 100%;" v-model="form.maxPrice" placeholder="0"></el-input>
              </el-col>
            </el-form-item>
            <el-button type="primary" class="cx" @click="getGoodList">查询</el-button>
            
          </el-form>
        </div>
      </div>
      <!-- 数据table -->
      <el-table ref="multipleTableContent" :data="pageData" stripe :header-cell-style="tableHeaderStyle"
       v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="42"></el-table-column>
        <el-table-column type="index" width="80" label="序号" align="center">
           <template scope="scope"><span>{{scope.$index+(form.pageNum - 1) * form.pageSize + 1}} </span></template>
        </el-table-column>
        <el-table-column prop="surfaceImg" label="商品图片">
          <template slot-scope="scope">
            <img :src="imgBaseUrl + scope.row.surfaceImg" class="shop_avator" width="100%" style="object-fit: cover;" v-if="scope.row.surfaceImg"/>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="商品名称"></el-table-column>
        <el-table-column prop="goodsNo" label="商品编码"></el-table-column>
        <el-table-column prop="categoryTitle" label="商品分类"></el-table-column>
        <el-table-column prop="minSupplyPrice" label="成本价（元）">
           <template slot-scope="scope">
             <span>{{scope.row.minSupplyPrice}}~{{scope.row.maxSupplyPrice}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minPrice" label="售价（元）">
           <template slot-scope="scope">
             <span>{{scope.row.minPrice}}~{{scope.row.maxPrice}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="showStore(scope.row.goodsId,scope.row.id)">设置</el-button>
            <el-button type="text" size="mini" @click="clickDelet(scope.row,scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
        <!-- 分页 -->
      <div class="text-center">
        <br>
          <el-pagination :page-sizes="[10, 50, 100, 200]" background :page-size="form.pageSize" :current-page="form.pageNum"
            layout="total, sizes, prev, pager, next, jumper" :total="pageCount" @current-change="paging" @size-change="handleSizeChange"> </el-pagination>
      </div>
      <!-- 设置弹窗 -->
      <el-dialog :visible.sync="dialogTableVisible" width="20%" :center=true>
        <h3 class="ysdx" slot="title" v-if="flang">批量设置商品分销信息</h3>
        <h3 class="ysdx" slot="title" v-else>设置商品分销信息</h3>
        <el-form >
          <el-form-item :label-width="formLabelWidth">
            <el-radio v-model="radio" label="1">使用默认<span style="margin-left:20px;">10%</span></el-radio>
          </el-form-item>
           <el-form-item :label-width="formLabelWidth">
            <el-radio v-model="radio" label="2">自定义设置 <el-input v-if="radio=='2'" @blur="salaryChange" v-model="saveForm.distRatio" style="width:50%" oninput="value=value.replace(/^\+|[^\d]/g,'')"></el-input></el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="ConfirmSave">确 定</el-button>
        </div>
    </el-dialog>
    </div>
  </div>
</div>
</template>

<script>
import Setting from '@/settings'
import { distributionList, deleteDistribution, BatchDeleteDistribution, saveGoodsSetting, batchSet, setDistributionStaus, setDistributionBatchStaus} from '@/api/distribution'
import {myMixin} from '@/layout/mixin/ResizeHandler'
import {getGoodsCategoryList,} from '@/api/setSharing'
export default {
  name:"adddistri",
  mixins:[myMixin],
  data() {
    return {
      pageNum:1,//分页页数
      pageSize:10,//分页行数
      dialogTableVisible:false,
      radio:"1",//单选框
      imgBaseUrl: `${process.env.VUE_APP_FILE_URL}/`,//图片地址
      setSatus:false,//设置的状态
      flang:false,//设置的状态
      // 查询条件
      form: {
        goodsName: null,//商品名
        minPrice: null,//最小售价
        maxPrice: null,//最大售价
        mchId:this.$store.getters.userInfo ? JSON.parse(this.$store.getters.userInfo).mchId : '1',
        selectType:3,
        pageNum: 1,
        pageSize: 10,
        categoryId:null,//商品分类
      },
       queryParams: { 
        pageNum: 1,
        pageSize: 10,
      },
      saveForm:{//设置传的参数
        goodsId:'',//商品id
        distRatio:'',//分销商品比列
        createTime:'',//创建时间
        creatorId:JSON.parse(this.$store.state.user.userInfo).id,//用户id
        id:'',//商品id
      },
      loading: false,
      multipleSelection: [],//全选数据
      tableHeaderStyle: Setting.tableHeaderStyle,
      pageData: [],
      categoryId:[],//分类数据
      options: [],
      pageCount: 0,
      formLabelWidth: '25%'
    }
  },
  created() {
    // this.distribution()
    this.getGoodList()
    this.saveForm.createTime = this.getNowFormatDate()//转换时间格式
    this.getGoodsCategoryList()
  },
  watch: {
      categoryId(val) {
        if (val.length != 0) {
          this.form.categoryId = val[val.length - 1]
          console.log( this.form.categoryId)
        }
      }
  },
  methods: {
    salaryChange(e){//input框触发
     this.saveForm.distRatio = e.target.value
    },
     getGoodsCategoryList() {
        getGoodsCategoryList().then(res => {
          if (res.code == 200) {
            this.options = res.data
          }
        })

      },    
   paging(val) {//分销商品列表分页操作
     this.form.pageNum =val
      this.getGoodList()
   },
   handleSizeChange(val) {
      this.form.pageSize = val 
      this.getGoodList()
   },
    handleSelectionChange(val) {//全选
      this.multipleSelection = val
      
    },
   async setUpdateShow(DistriId) {//修改自营里分销状态
      let res = await setDistributionStaus({
            mchId:this.$store.getters.userInfo ? JSON.parse(this.$store.getters.userInfo).mchId : '1',
            id:DistriId,
            isDistribution:0,
          })
    },
    async setDisBackShow (id) {//批量修改自营里分销状态
      let res = await setDistributionBatchStaus({
          mchId:this.$store.getters.userInfo ? JSON.parse(this.$store.getters.userInfo).mchId : '1',
          targetIds:id,
          isDistribution:0,
      })
    },
  clickDelet(item,index) {//删除分销商品
        this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        }).then(() => {
           deleteDistribution({id:item.id}).then(res => {
            if(res.code == 200){
            this.pageData.splice(index, 1)
            this.$message({ message: '删除商品成功', type: 'success'});
            this.setUpdateShow(item.goodsId)
            this.getGoodList()
          }
           })
         
        })
    },
     showStore(goodsId,id) {//打开设置弹窗
      this.setSatus = true
      this.dialogTableVisible = true
      this.saveForm.goodsId = goodsId
      this.saveForm.id = id
    },
    async ConfirmSave() {//设置分销比例
    if(!this.multipleSelection || !this.multipleSelection.length){//单个设置
       if(this.radio == "1") {
        this.saveForm.distRatio = 10
      }
       let res = await saveGoodsSetting(this.saveForm)
       if(res.code == 200) {
          this.setSatus = false
          this.$message({ message: '设置分销比例成功', type: 'success'});
          this.saveForm.distRatio = ''
          this.dialogTableVisible = false
       }
    }else{//批量设置
      let res = await batchSet(this.saveForm)
      if(res.code == 200) {
        this.$message({ message: '批量设置商品成功', type: 'success'});
        this.dialogTableVisible = false
        this.getGoodList()
    }
    }
     
    },
    cancel() {//取消
       this.dialogTableVisible = false
       this.getGoodList()
    },
    BatchDelel() {//批量删除
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请选择需要删除的商品!'
        });
        return;
      }
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
          BatchDeleteDistribution({
            id:this.multipleSelection.map(item => item.id).join(',')
          }).then(res => {
            if(res.code == 200){
              this.$message({ message: '删除商品成功', type: 'success'});
              this.setDisBackShow(this.multipleSelection.map(item => item.goodsId).join(','))
              this.getGoodList()
            }
           
          })
        })
    },
   VolumeSet() {//批量设置
        if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请选择需要批量设置的商品!'
        });
        return;
      }else{
        this.dialogTableVisible = true
         this.flang = true
        this.saveForm.goodsId = this.multipleSelection.map(item => item.goodsId).join(',')
         this.saveForm.id = this.multipleSelection.map(item => item.id).join(',')
        console.log( this.multipleSelection )
         if(this.radio == "1") {
          this.saveForm.distRatio = 10
      }
      }
    
    },
    backMarket() {//返回分销市场
        this.$router.push({
        name:'DistributionMarket'
      })
    },
    addgoods(){ //添加商品跳转
      this.$router.push('/store/list')
    },
  
    // showStore(item) {//设置
    //   this.flang = true
    //   this.BeforeData = item
    //   console.log(this.BeforeData)
    // },
    async getGoodList() {//我的供货查询
      // this.loading = true;
      const res = await distributionList(this.form)
       if(res.code == 200){
        // setTimeout(() => {
        //   this.loading = false;
        // }, 500);
         if(this.form.goodsName || this.form.minPrice) {
           this.form = {}
         }
         this.categoryId=''
         this.pageData = res.data.list
         this.pageCount = res.data.total;
         this.form.pageSize = res.data.pageSize
          this.form.pageNum = res.data.pageNum
      }else {
          this.loading = false;
          this.$message.error('加载失败，请重新刷新列表');
          return;
        }
    },
  }

  
}
</script>

<style lang="scss" scoped>
.app-page {
  height: auto;
  border-radius: 6px;
  box-shadow: 0 0 4px 0 rgba(200, 200, 200, 0.5);
}

.page-header,
.page-body {
  padding: 22px 20px;
}

.page-body {
  padding-top: 0px;
  border-radius: 6px;
    background: #fff;
    -webkit-box-shadow: 0 0 4px 0 rgba(200, 200, 200, 0.5);
    box-shadow: 0 0 4px 0 rgba(200, 200, 200, 0.5);
}

.shop_avator {
  width: 64px;
  height: 64px;
}
.full-width {
    margin-top: 20px;
}
.cx{
  margin-top: -2px;
}
::v-deep .el-table th > .cell{
  text-align: center;
}
::v-deep .el-col-2 {
    text-align: center;
    color: #c2c2c2;
}
::v-deep .el-table .cell{
  text-align: center;
}
.buttonDel{
  display:inline-block;
  margin-left:7rem;
}
</style>
